/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.controller.v2;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csp.sentinel.dashboard.auth.AuthAction;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.client.SentinelApiClient;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntityV2;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.rule.zookeeper.degrade.ZookeeperDegradeRuleStore;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
import com.alibaba.csp.sentinel.util.StringUtil;

/**
 * @author fenglibin
 */
@RestController
@RequestMapping(value = "/degrade")
public class DegradeControllerV2 {

	private final Logger logger = LoggerFactory.getLogger(DegradeControllerV2.class);

	@Autowired
	private ZookeeperDegradeRuleStore<DegradeRuleEntity> repository;
	@Autowired
	private SentinelApiClient sentinelApiClient;

	/**
	 * 查询
	 */
	@ResponseBody
	@RequestMapping("/rules.json")
	@AuthAction(PrivilegeType.READ_RULE)
	public Result<List<DegradeRuleEntityV2>> queryRules(String app, String ip, Integer port) {

		if (StringUtil.isEmpty(app)) {
			return Result.ofFail(-1, "app can't be null or empty");
		}
		try {
			List<DegradeRuleEntity> rules = null;
			// 根据应用查询规则
			rules = repository.findAllByApp(app);
			final List<DegradeRuleEntityV2> list = new ArrayList<DegradeRuleEntityV2>();
			if (rules != null && rules.size() > 0) {
				rules.forEach(r -> {
					list.add(r.getDegradeRuleEntityV2());
				});
			}
			return Result.ofSuccess(list);
		} catch (Throwable throwable) {
			logger.error("queryApps error:", throwable);
			return Result.ofThrowable(-1, throwable);
		}
	}

	/**
	 * 新增
	 * @param entity
	 * @return
	 */
	@PostMapping("/rule")
	@AuthAction(PrivilegeType.WRITE_RULE)
	public Result<DegradeRuleEntity> apiAddRule(@RequestBody DegradeRuleEntity entity) {
		Result<DegradeRuleEntity> checkResult = checkEntityInternal(entity);
		if (checkResult != null) {
			return checkResult;
		}
		Date date = new Date();
		entity.setGmtCreate(date);
		entity.setGmtModified(date);
		try {
			entity = repository.save(entity);
		} catch (Throwable t) {
			logger.error("Failed to add new degrade rule, app={}, ip={}", entity.getApp(), entity.getIp(), t);
			return Result.ofThrowable(-1, t);
		}
		if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) {
			logger.warn("Publish degrade rules failed, app={}", entity.getApp());
		}
		return Result.ofSuccess(entity);
	}
	/**
	 * 更新
	 * @param id
	 * @param entity
	 * @return
	 */
	@PutMapping("/rule/{id}")
	@AuthAction(PrivilegeType.WRITE_RULE)
	public Result<DegradeRuleEntity> apiUpdateRule(@PathVariable("id") Long id, @RequestBody DegradeRuleEntity entity) {
		if (id == null || id <= 0) {
			return Result.ofFail(-1, "id can't be null or negative");
		}
		DegradeRuleEntity oldEntity = repository.findById(id);
		if (oldEntity == null) {
			return Result.ofFail(-1, "Degrade rule does not exist, id=" + id);
		}
		entity.setApp(oldEntity.getApp());
		entity.setIp(oldEntity.getIp());
		entity.setPort(oldEntity.getPort());
		entity.setId(oldEntity.getId());
		Result<DegradeRuleEntity> checkResult = checkEntityInternal(entity);
		if (checkResult != null) {
			return checkResult;
		}

		entity.setGmtCreate(oldEntity.getGmtCreate());
		entity.setGmtModified(new Date());
		try {
			entity = repository.save(entity);
		} catch (Throwable t) {
			logger.error("Failed to save degrade rule, id={}, rule={}", id, entity, t);
			return Result.ofThrowable(-1, t);
		}
		if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) {
			logger.warn("Publish degrade rules failed, app={}", entity.getApp());
		}
		return Result.ofSuccess(entity);
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@DeleteMapping("/rule/{id}")
	@AuthAction(PrivilegeType.DELETE_RULE)
	public Result<Long> delete(@PathVariable("id") Long id) {
		if (id == null) {
			return Result.ofFail(-1, "id can't be null");
		}

		DegradeRuleEntity oldEntity = repository.findById(id);
		if (oldEntity == null) {
			return Result.ofSuccess(null);
		}

		try {
			repository.delete(id);
		} catch (Throwable throwable) {
			logger.error("Failed to delete degrade rule, id={}", id, throwable);
			return Result.ofThrowable(-1, throwable);
		}
		if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) {
			logger.warn("Publish degrade rules failed, app={}", oldEntity.getApp());
		}
		return Result.ofSuccess(id);
	}

	private boolean publishRules(String app, String ip, Integer port) {
		List<DegradeRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));
		return sentinelApiClient.setDegradeRuleOfMachine(app, ip, port, rules);
	}

	private <R> Result<R> checkEntityInternal(DegradeRuleEntity entity) {
		if (StringUtil.isBlank(entity.getApp())) {
			return Result.ofFail(-1, "app can't be blank");
		}
		if (StringUtil.isBlank(entity.getLimitApp())) {
			return Result.ofFail(-1, "limitApp can't be null or empty");
		}
		if (StringUtil.isBlank(entity.getResource())) {
			return Result.ofFail(-1, "resource can't be null or empty");
		}
		Double threshold = entity.getCount();
		if (threshold == null || threshold < 0) {
			return Result.ofFail(-1, "invalid threshold: " + threshold);
		}
		Integer recoveryTimeoutSec = entity.getTimeWindow();
		if (recoveryTimeoutSec == null || recoveryTimeoutSec <= 0) {
			return Result.ofFail(-1, "recoveryTimeout should be positive");
		}
		Integer strategy = entity.getGrade();
		if (strategy == null) {
			return Result.ofFail(-1, "circuit breaker strategy cannot be null");
		}
		if (strategy < CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType()
				|| strategy > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) {
			return Result.ofFail(-1, "Invalid circuit breaker strategy: " + strategy);
		}
		if (entity.getMinRequestAmount() == null || entity.getMinRequestAmount() <= 0) {
			return Result.ofFail(-1, "Invalid minRequestAmount");
		}
		if (entity.getStatIntervalMs() == null || entity.getStatIntervalMs() <= 0) {
			return Result.ofFail(-1, "Invalid statInterval");
		}
		if (strategy == RuleConstant.DEGRADE_GRADE_RT) {
			Double slowRatio = entity.getSlowRatioThreshold();
			if (slowRatio == null) {
				return Result.ofFail(-1, "SlowRatioThreshold is required for slow request ratio strategy");
			} else if (slowRatio < 0 || slowRatio > 1) {
				return Result.ofFail(-1, "SlowRatioThreshold should be in range: [0.0, 1.0]");
			}
		} else if (strategy == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {
			if (threshold > 1) {
				return Result.ofFail(-1, "Ratio threshold should be in range: [0.0, 1.0]");
			}
		}
		return null;
	}

	@Deprecated
	@ResponseBody
	@RequestMapping("/new.json")
	@AuthAction(PrivilegeType.WRITE_RULE)
	public Result<DegradeRuleEntityV2> add(String app, String ip, Integer port, String limitApp, String resource,
			Double count, Integer timeWindow, Integer grade) {
		if (StringUtil.isBlank(app)) {
			return Result.ofFail(-1, "app can't be null or empty");
		}
		if (StringUtil.isBlank(ip)) {
			return Result.ofFail(-1, "ip can't be null or empty");
		}
		if (port == null) {
			return Result.ofFail(-1, "port can't be null");
		}
		if (StringUtil.isBlank(limitApp)) {
			return Result.ofFail(-1, "limitApp can't be null or empty");
		}
		if (StringUtil.isBlank(resource)) {
			return Result.ofFail(-1, "resource can't be null or empty");
		}
		if (count == null) {
			return Result.ofFail(-1, "count can't be null");
		}
		if (timeWindow == null) {
			return Result.ofFail(-1, "timeWindow can't be null");
		}
		if (grade == null) {
			return Result.ofFail(-1, "grade can't be null");
		}
		if (grade < RuleConstant.DEGRADE_GRADE_RT || grade > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) {
			return Result.ofFail(-1, "Invalid grade: " + grade);
		}
		DegradeRuleEntity entity = new DegradeRuleEntity();
		entity.setApp(app.trim());
		entity.setIp(ip.trim());
		entity.setPort(port);
		entity.setLimitApp(limitApp.trim());
		entity.setResource(resource.trim());
		entity.setCount(count);
		entity.setTimeWindow(timeWindow);
		entity.setGrade(grade);
		Date date = new Date();
		entity.setGmtCreate(date);
		entity.setGmtModified(date);
		try {
			entity = repository.save(entity);
		} catch (Throwable throwable) {
			logger.error("add error:", throwable);
			return Result.ofThrowable(-1, throwable);
		}
		return Result.ofSuccess(entity.getDegradeRuleEntityV2());
	}

	@Deprecated
	@ResponseBody
	@RequestMapping("/save.json")
	@AuthAction(PrivilegeType.WRITE_RULE)
	public Result<DegradeRuleEntityV2> updateIfNotNull(Long id, String app, String limitApp, String resource,
			Double count, Integer timeWindow, Integer grade) {
		if (id == null) {
			return Result.ofFail(-1, "id can't be null");
		}
		if (grade != null) {
			if (grade < RuleConstant.DEGRADE_GRADE_RT || grade > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) {
				return Result.ofFail(-1, "Invalid grade: " + grade);
			}
		}
		DegradeRuleEntity entity = repository.findById(id);
		if (entity == null) {
			return Result.ofFail(-1, "id " + id + " dose not exist");
		}

		if (StringUtil.isNotBlank(app)) {
			entity.setApp(app.trim());
		}

		if (StringUtil.isNotBlank(limitApp)) {
			entity.setLimitApp(limitApp.trim());
		}
		if (StringUtil.isNotBlank(resource)) {
			entity.setResource(resource.trim());
		}
		if (count != null) {
			entity.setCount(count);
		}
		if (timeWindow != null) {
			entity.setTimeWindow(timeWindow);
		}
		if (grade != null) {
			entity.setGrade(grade);
		}
		Date date = new Date();
		entity.setGmtModified(date);
		try {
			entity = repository.save(entity);
		} catch (Throwable throwable) {
			logger.error("save error:", throwable);
			return Result.ofThrowable(-1, throwable);
		}
		return Result.ofSuccess(entity.getDegradeRuleEntityV2());
	}

	@Deprecated
	/**
	 * 用于支持1.8.0以前的控制台
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete.json")
	@AuthAction(PrivilegeType.DELETE_RULE)
	public Result<Long> delete0(Long id) {
		if (id == null) {
			return Result.ofFail(-1, "id can't be null");
		}

		DegradeRuleEntity oldEntity = repository.findById(id);
		if (oldEntity == null) {
			return Result.ofSuccess(null);
		}

		try {
			repository.delete(id);
		} catch (Throwable throwable) {
			logger.error("delete error:", throwable);
			return Result.ofThrowable(-1, throwable);
		}
		return Result.ofSuccess(id);
	}
}
